package JUC.future;

import org.junit.Test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author mubei
 * @date 2021/11/23
 * @description
 * 异步调用:CompletableFuture
 * y异步执行
 * 成功回调
 * 失败回调
 */
public class Demo01 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //没有返回值的异步回调
        CompletableFuture<Void> comp = CompletableFuture.runAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"runAsync=>Void");
        });

        System.out.println("111");
        comp.get();
        System.out.println("222");



    }


    @Test()
    public void test2() throws ExecutionException, InterruptedException {
        // 有返回值的异步回调
        CompletableFuture<Integer> comp2 = CompletableFuture.supplyAsync(()->1024);
        System.out.println(comp2.whenComplete((t1, t2) -> {
            System.out.println(t1);//正常的返回结果
            System.out.println(t2);//错误信息
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return 233;//错误的返回结果
        }).get());
        System.out.println(comp2.get());
    }
}
